package cn.cxy.contentproviderdemo

import android.database.ContentObserver
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val uri: Uri = Uri.parse("content://cn.cxy.contentproviderdemo.provider/user")
        contentResolver.registerContentObserver(uri, false, object : ContentObserver(Handler()) {
            override fun onChange(selfChange: Boolean) {
                queryUser()
            }
        })
    }

    /**
     * 查询数据
     */
    private fun queryUser() {
        Log.d("MainActivity", "数据有变，重新查询。")
        GlobalScope.launch(Dispatchers.IO) {
            val uri = Uri.parse("content://cn.cxy.contentproviderdemo.provider/user")
            val cursor = contentResolver.query(uri, null, null, null, null)
            if (cursor != null) {
                var count = 0
                while (cursor.moveToNext()) {
                    val id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"))
                    val name = cursor.getString(cursor.getColumnIndexOrThrow("user_name"))
                    Log.d("MainActivity", "用户：${id}_$name")
                    count++
                }
                cursor.close()
                if (count == 0) {
                    Log.d("MainActivity", "数据库是空的！")
                }
            }
        }
    }
}